home *** CD-ROM | disk | FTP | other *** search
/ Meeting Pearls 1 / Meeting Pearls Vol 1 (1994).iso / installed_progs / text / faqs / perl-faq.part3 < prev    next >
Encoding:
Internet Message Format  |  1993-10-03  |  42.8 KB

  1. Subject: Perl Frequently Asked Questions, part 3 of 4
  2. Newsgroups: comp.lang.perl,news.answers
  3. From: Tom Christiansen <tchrist@cs.Colorado.EDU>
  4. Date: Sat, 2 Oct 1993 06:37:56 GMT
  5.  
  6. Archive-name: perl-faq/part3
  7. Version: $Id: perl-tech1,v 1.1 93/10/02 00:27:00 tchrist Exp Locker: tchrist $
  8.  
  9. This posting contains answers to the following technical questions
  10. regarding Perl:
  11.  
  12. 2.1) What are all these $@*%<> signs and how do I know when to use them?
  13. 2.2) Why don't backticks work as they do in shells?  
  14. 2.3) How come Perl operators have different precedence than C operators?
  15. 2.4) How come my converted awk/sed/sh script runs more slowly in Perl?
  16. 2.5) How can I call my system's unique C functions from Perl?
  17. 2.6) Where do I get the include files to do ioctl() or syscall()?
  18. 2.7) Why doesn't "local($foo) = <FILE>;" work right?
  19. 2.8) How can I detect keyboard input without reading it, 
  20. 2.9) how can I read a single character from the keyboard under UNIX and DOS?
  21. 2.10) How can I make an array of arrays or other recursive data types?
  22. 2.11) How do I make an array of structures containing various data types?
  23. 2.12) How can I quote a variable to use in a regexp?
  24. 2.13) Why do setuid Perl scripts complain about kernel problems?
  25. 2.14) How do I open a pipe both to and from a command?
  26. 2.15) How can I change the first N letters of a string?
  27. 2.16) How can I manipulate fixed-record-length files?
  28. 2.17) How can I make a file handle local to a subroutine?
  29. 2.18) How can I extract just the unique elements of an array?
  30. 2.19) How can I call alarm() or usleep() from Perl?
  31. 2.20) How can I test whether an array contains a certain element?
  32. 2.21) How can I do an atexit() or setjmp()/longjmp() in Perl?
  33. 2.22) Why doesn't Perl interpret my octal data octally?
  34. 2.23) How do I sort an associative array by value instead of by key?
  35. 2.24) How can I capture STDERR from an external command?
  36. 2.25) Why doesn't open return an error when a pipe open fails?
  37. 2.26) How can I compare two date strings?
  38. 2.27) What's the fastest way to code up a given task in perl?
  39. 2.28) How can I know how many entries are in an associative array?
  40.  
  41.  
  42. 2.1) What are all these $@*%<> signs and how do I know when to use them?
  43.  
  44.     Those are type specifiers: $ for scalar values, @ for indexed arrays,
  45.     and % for hashed arrays.  The * means all types of that symbol name
  46.     and are sometimes used like pointers; the <> are used for inputting
  47.     a record from a filehandle.  See the question on arrays of arrays
  48.     for more about Perl pointers.
  49.  
  50.     Always make sure to use a $ for single values and @ for multiple ones.
  51.     Thus element 2 of the @foo array is accessed as $foo[2], not @foo[2],
  52.     which is a list of length one (not a scalar), and is a fairly common
  53.     novice mistake.  Sometimes you can get by with @foo[2], but it's
  54.     not really doing what you think it's doing for the reason you think
  55.     it's doing it, which means one of these days, you'll shoot yourself
  56.     in the foot; ponder for a moment what these will really do:
  57.     @foo[0] = `cmd args`;
  58.     @foo[2] = <FILE>;
  59.     Just always say $foo[2] and you'll be happier.
  60.  
  61.     This may seem confusing, but try to think of it this way:  you use the
  62.     character of the type which you *want back*.  You could use @foo[1..3] for
  63.     a slice of three elements of @foo, or even @foo{A,B,C} for a slice of
  64.     of %foo.  This is the same as using ($foo[1], $foo[2], $foo[3]) and
  65.     ($foo{A}, $foo{B}, $foo{C}) respectively.  In fact, you can even use
  66.     lists to subscript arrays and pull out more lists, like @foo[@bar] or
  67.     @foo{@bar}, where @bar is in both cases presumably a list of subscripts.
  68.  
  69.     While there are a few places where you don't actually need these type
  70.     specifiers, except for files, you should always use them.  Note that
  71.     <FILE> is NOT the type specifier for files; it's the equivalent of awk's
  72.     getline function, that is, it reads a line from the handle FILE.  When
  73.     doing open, close, and other operations besides the getline function on
  74.     files, do NOT use the brackets.
  75.  
  76.     Beware of saying:
  77.     $foo = BAR;
  78.     Which wil be interpreted as 
  79.     $foo = 'BAR';
  80.     and not as 
  81.     $foo = <BAR>;
  82.     If you always quote your strings, you'll avoid this trap.
  83.  
  84.     Normally, files are manipulated something like this (with appropriate
  85.     error checking added if it were production code):
  86.  
  87.     open (FILE, ">/tmp/foo.$$");
  88.     print FILE "string\n";
  89.     close FILE;
  90.  
  91.     If instead of a filehandle, you use a normal scalar variable with file
  92.     manipulation functions, this is considered an indirect reference to a
  93.     filehandle.  For example,
  94.  
  95.     $foo = "TEST01";
  96.     open($foo, "file");
  97.  
  98.     After the open, these two while loops are equivalent:
  99.  
  100.     while (<$foo>) {}
  101.     while (<TEST01>) {}
  102.  
  103.     as are these two statements:
  104.     
  105.     close $foo;
  106.     close TEST01;
  107.  
  108.     but NOT to this:
  109.  
  110.     while (<$TEST01>) {} # error
  111.         ^
  112.         ^ note spurious dollar sign
  113.  
  114.     This is another common novice mistake; often it's assumed that
  115.  
  116.     open($foo, "output.$$");
  117.  
  118.     will fill in the value of $foo, which was previously undefined.  
  119.     This just isn't so -- you must set $foo to be the name of a valid
  120.     filehandle before you attempt to open it.
  121.  
  122.  
  123. 2.2) Why don't backticks work as they do in shells?  
  124.  
  125.     Several reason.  One is because backticks do not interpolate within
  126.     double quotes in Perl as they do in shells.  
  127.     
  128.     Let's look at two common mistakes:
  129.  
  130.          $foo = "$bar is `wc $file`";  # WRONG
  131.  
  132.     This should have been:
  133.  
  134.      $foo = "$bar is " . `wc $file`;
  135.  
  136.     But you'll have an extra newline you might not expect.  This
  137.     does not work as expected:
  138.  
  139.       $back = `pwd`; chdir($somewhere); chdir($back); # WRONG
  140.  
  141.     Because backticks do not automatically eat trailing or embedded
  142.     newlines.  The chop() function will remove the last character from
  143.     a string.  This should have been:
  144.  
  145.       chop($back = `pwd`); chdir($somewhere); chdir($back);
  146.  
  147.     You should also be aware that while in the shells, embedding
  148.     single quotes will protect variables, in Perl, you'll need 
  149.     to escape the dollar signs.
  150.  
  151.     Shell: foo=`cmd 'safe $dollar'`
  152.     Perl:  $foo=`cmd 'safe \$dollar'`;
  153.     
  154.  
  155. 2.3) How come Perl operators have different precedence than C operators?
  156.  
  157.     Actually, they don't; all C operators have the same precedence in Perl as
  158.     they do in C.  The problem is with a class of functions called list
  159.     operators, e.g. print, chdir, exec, system, and so on.  These are somewhat
  160.     bizarre in that they have different precedence depending on whether you
  161.     look on the left or right of them.  Basically, they gobble up all things
  162.     on their right.  For example,
  163.  
  164.     unlink $foo, "bar", @names, "others";
  165.  
  166.     will unlink all those file names.  A common mistake is to write:
  167.  
  168.     unlink "a_file" || die "snafu";
  169.  
  170.     The problem is that this gets interpreted as
  171.  
  172.     unlink("a_file" || die "snafu");
  173.  
  174.     To avoid this problem, you can always make them look like function calls
  175.     or use an extra level of parentheses:
  176.  
  177.     (unlink "a_file") || die "snafu";
  178.     unlink("a_file")  || die "snafu";
  179.  
  180.     Sometimes you actually do care about the return value:
  181.  
  182.     unless ($io_ok = print("some", "list")) { } 
  183.  
  184.     Yes, print() return I/O success.  That means
  185.  
  186.     $io_ok = print(2+4) * 5;
  187.  
  188.     returns 5 times whether printing (2+4) succeeded, and 
  189.     print(2+4) * 5;
  190.     returns the same 5*io_success value and tosses it.
  191.  
  192.     See the Perl man page's section on Precedence for more gory details,
  193.     and be sure to use the -w flag to catch things like this.
  194.  
  195.  
  196. 2.4) How come my converted awk/sed/sh script runs more slowly in Perl?
  197.  
  198.     The natural way to program in those languages may not make for the fastest
  199.     Perl code.  Notably, the awk-to-perl translator produces sub-optimal code;
  200.     see the a2p man page for tweaks you can make.
  201.  
  202.     Two of Perl's strongest points are its associative arrays and its regular
  203.     expressions.  They can dramatically speed up your code when applied
  204.     properly.  Recasting your code to use them can help a lot.
  205.  
  206.     How complex are your regexps?  Deeply nested sub-expressions with {n,m} or
  207.     * operators can take a very long time to compute.  Don't use ()'s unless
  208.     you really need them.  Anchor your string to the front if you can.
  209.  
  210.     Something like this:
  211.     next unless /^.*%.*$/; 
  212.     runs more slowly than the equivalent:
  213.     next unless /%/;
  214.  
  215.     Note that this:
  216.     next if /Mon/;
  217.     next if /Tue/;
  218.     next if /Wed/;
  219.     next if /Thu/;
  220.     next if /Fri/;
  221.     runs faster than this:
  222.     next if /Mon/ || /Tue/ || /Wed/ || /Thu/ || /Fri/;
  223.     which in turn runs faster than this:
  224.     next if /Mon|Tue|Wed|Thu|Fri/;
  225.     which runs *much* faster than:
  226.     next if /(Mon|Tue|Wed|Thu|Fri)/;
  227.  
  228.     There's no need to use /^.*foo.*$/ when /foo/ will do.
  229.  
  230.     Remember that a printf costs more than a simple print.
  231.  
  232.     Don't split() every line if you don't have to.
  233.  
  234.     Another thing to look at is your loops.  Are you iterating through 
  235.     indexed arrays rather than just putting everything into a hashed 
  236.     array?  For example,
  237.  
  238.     @list = ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stv');
  239.  
  240.     for $i ($[ .. $#list) {
  241.         if ($pattern eq $list[$i]) { $found++; } 
  242.     } 
  243.  
  244.     First of all, it would be faster to use Perl's foreach mechanism
  245.     instead of using subscripts:
  246.  
  247.     foreach $elt (@list) {
  248.         if ($pattern eq $elt) { $found++; } 
  249.     } 
  250.  
  251.     Better yet, this could be sped up dramatically by placing the whole
  252.     thing in an associative array like this:
  253.  
  254.     %list = ('abc', 1, 'def', 1, 'ghi', 1, 'jkl', 1, 
  255.          'mno', 1, 'pqr', 1, 'stv', 1 );
  256.     $found += $list{$pattern};
  257.     
  258.     (but put the %list assignment outside of your input loop.)
  259.  
  260.     You should also look at variables in regular expressions, which is
  261.     expensive.  If the variable to be interpolated doesn't change over the
  262.     life of the process, use the /o modifier to tell Perl to compile the
  263.     regexp only once, like this:
  264.  
  265.     for $i (1..100) {
  266.         if (/$foo/o) {
  267.         &some_func($i);
  268.         } 
  269.     } 
  270.  
  271.     Finally, if you have a bunch of patterns in a list that you'd like to 
  272.     compare against, instead of doing this:
  273.  
  274.     @pats = ('_get.*', 'bogus', '_read', '.*exit', '_write');
  275.     foreach $pat (@pats) {
  276.         if ( $name =~ /^$pat$/ ) {
  277.         &some_func();
  278.         last;
  279.         }
  280.     }
  281.  
  282.     If you build your code and then eval it, it will be much faster.
  283.     For example:
  284.  
  285.     @pats = ('_get.*', 'bogus', '_read', '.*exit', '_write');
  286.     $code = <<EOS
  287.         while (<>) { 
  288.             study;
  289. EOS
  290.     foreach $pat (@pats) {
  291.         $code .= <<EOS
  292.         if ( /^$pat\$/ ) {
  293.             &some_func();
  294.             next;
  295.         }
  296. EOS
  297.     }
  298.     $code .= "}\n";
  299.     print $code if $debugging;
  300.     eval $code;
  301.  
  302.  
  303.  
  304. 2.5) How can I call my system's unique C functions from Perl?
  305.  
  306.     If these are system calls and you have the syscall() function, then
  307.     you're probably in luck -- see the next question.  For arbitrary
  308.     library functions, it's not quite so straight-forward.  While you
  309.     can't have a C main and link in Perl routines, if you're
  310.     determined, you can extend Perl by linking in your own C routines.
  311.     See the usub/ subdirectory in the Perl distribution kit for an example
  312.     of doing this to build a Perl that understands curses functions.  It's
  313.     neither particularly easy nor overly-documented, but it is feasible.
  314.  
  315.  
  316. 2.6) Where do I get the include files to do ioctl() or syscall()?
  317.  
  318.     These are generated from your system's C include files using the h2ph
  319.     script (once called makelib) from the Perl source directory.  This will
  320.     make files containing subroutine definitions, like &SYS_getitimer, which
  321.     you can use as arguments to your function.
  322.  
  323.     You might also look at the h2pl subdirectory in the Perl source for how to
  324.     convert these to forms like $SYS_getitimer; there are both advantages and
  325.     disadvantages to this.  Read the notes in that directory for details.  
  326.    
  327.     In both cases, you may well have to fiddle with it to make these work; it
  328.     depends how funny-looking your system's C include files happen to be.
  329.  
  330.     If you're trying to get at C structures, then you should take a look
  331.     at using c2ph, which uses debugger "stab" entries generated by your
  332.     BSD or GNU C compiler to produce machine-independent perl definitions
  333.     for the data structures.  This allows to you avoid hardcoding
  334.     structure layouts, types, padding, or sizes, greatly enhancing
  335.     portability.  c2ph comes with the perl distribution.  On an SCO
  336.     system, GCC only has COFF debugging support by default, so you'll have
  337.     to build GCC 2.1 with DBX_DEBUGGING_INFO defined, and use -gstabs to
  338.     get c2ph to work there.
  339.  
  340.     See the file /pub/perl/info/ch2ph on convex.com via anon ftp 
  341.     for more traps and tips on this process.
  342.  
  343.  
  344. 2.7) Why doesn't "local($foo) = <FILE>;" work right?
  345.  
  346.     Well, it does.  The thing to remember is that local() provides an array
  347.     context, and that the <FILE> syntax in an array context will read all the
  348.     lines in a file.  To work around this, use:
  349.  
  350.     local($foo);
  351.     $foo = <FILE>;
  352.  
  353.     You can use the scalar() operator to cast the expression into a scalar
  354.     context:
  355.  
  356.     local($foo) = scalar(<FILE>);
  357.  
  358.  
  359. 2.8) How can I detect keyboard input without reading it? 
  360.  
  361.     You should check out the Frequently Asked Questions list in
  362.     comp.unix.* for things like this: the answer is essentially the same.
  363.     It's very system dependent.  Here's one solution that works on BSD
  364.     systems:
  365.  
  366.     sub key_ready {
  367.         local($rin, $nfd);
  368.         vec($rin, fileno(STDIN), 1) = 1;
  369.         return $nfd = select($rin,undef,undef,0);
  370.     }
  371.  
  372.  
  373. 2.9) How can I read a single character from the keyboard under UNIX and DOS?
  374.  
  375.     A closely related question to the no-echo question is how to input a
  376.     single character from the keyboard.  Again, this is a system dependent
  377.     operation.  The following code that may or may not help you.  It should
  378.     work on both SysV and BSD flavors of UNIX:
  379.  
  380.     $BSD = -f '/vmunix';
  381.     if ($BSD) {
  382.         system "stty cbreak </dev/tty >/dev/tty 2>&1";
  383.     }
  384.     else {
  385.         system "stty", '-icanon',
  386.         system "stty", 'eol', "\001"; 
  387.     }
  388.  
  389.     $key = getc(STDIN);
  390.  
  391.     if ($BSD) {
  392.         system "stty -cbreak </dev/tty >/dev/tty 2>&1";
  393.     }
  394.     else {
  395.         system "stty", 'icanon';
  396.         system "stty", 'eol', '^@'; # ascii null
  397.     }
  398.     print "\n";
  399.  
  400.     You could also handle the stty operations yourself for speed if you're
  401.     going to be doing a lot of them.  This code works to toggle cbreak
  402.     and echo modes on a BSD system:
  403.  
  404.     sub set_cbreak { # &set_cbreak(1) or &set_cbreak(0)
  405.     local($on) = $_[0];
  406.     local($sgttyb,@ary);
  407.     require 'sys/ioctl.ph';
  408.     $sgttyb_t   = 'C4 S' unless $sgttyb_t;  # c2ph: &sgttyb'typedef()
  409.  
  410.     ioctl(STDIN,&TIOCGETP,$sgttyb) || die "Can't ioctl TIOCGETP: $!";
  411.  
  412.     @ary = unpack($sgttyb_t,$sgttyb);
  413.     if ($on) {
  414.         $ary[4] |= &CBREAK;
  415.         $ary[4] &= ~&ECHO;
  416.     } else {
  417.         $ary[4] &= ~&CBREAK;
  418.         $ary[4] |= &ECHO;
  419.     }
  420.     $sgttyb = pack($sgttyb_t,@ary);
  421.  
  422.     ioctl(STDIN,&TIOCSETP,$sgttyb) || die "Can't ioctl TIOCSETP: $!";
  423.     }
  424.  
  425.     Note that this is one of the few times you actually want to use the
  426.     getc() function; it's in general way too expensive to call for normal
  427.     I/O.  Normally, you just use the <FILE> syntax, or perhaps the read()
  428.     or sysread() functions.
  429.  
  430.     For perspectives on more portable solutions, use anon ftp to retrieve
  431.     the file /pub/perl/info/keypress from convex.com.
  432.  
  433.     For DOS systems, Dan Carson <dbc@tc.fluke.COM> reports:
  434.  
  435.     To put the PC in "raw" mode, use ioctl with some magic numbers gleaned
  436.     from msdos.c (Perl source file) and Ralf Brown's interrupt list (comes
  437.     across the net every so often):
  438.  
  439.     $old_ioctl = ioctl(STDIN,0,0);     # Gets device info
  440.     $old_ioctl &= 0xff;
  441.     ioctl(STDIN,1,$old_ioctl | 32);    # Writes it back, setting bit 5
  442.  
  443.     Then to read a single character:
  444.  
  445.     sysread(STDIN,$c,1);               # Read a single character
  446.  
  447.     And to put the PC back to "cooked" mode:
  448.  
  449.     ioctl(STDIN,1,$old_ioctl);         # Sets it back to cooked mode.
  450.  
  451.  
  452.     So now you have $c.  If ord($c) == 0, you have a two byte code, which
  453.     means you hit a special key.  Read another byte (sysread(STDIN,$c,1)),
  454.     and that value tells you what combination it was according to this
  455.     table:
  456.  
  457.     # PC 2-byte keycodes = ^@ + the following:
  458.  
  459.     # HEX     KEYS
  460.     # ---     ----
  461.     # 0F      SHF TAB
  462.     # 10-19   ALT QWERTYUIOP
  463.     # 1E-26   ALT ASDFGHJKL
  464.     # 2C-32   ALT ZXCVBNM
  465.     # 3B-44   F1-F10
  466.     # 47-49   HOME,UP,PgUp
  467.     # 4B      LEFT
  468.     # 4D      RIGHT
  469.     # 4F-53   END,DOWN,PgDn,Ins,Del
  470.     # 54-5D   SHF F1-F10
  471.     # 5E-67   CTR F1-F10
  472.     # 68-71   ALT F1-F10
  473.     # 73-77   CTR LEFT,RIGHT,END,PgDn,HOME
  474.     # 78-83   ALT 1234567890-=
  475.     # 84      CTR PgUp
  476.  
  477.     This is all trial and error I did a long time ago, I hope I'm reading the
  478.     file that worked.
  479.  
  480.  
  481. 2.10) How can I make an array of arrays or other recursive data types?
  482.  
  483.     Remember that Perl isn't about nested data structures (actually,
  484.     perl0 ..  perl4 weren't, but maybe perl5 will be, at least
  485.     somewhat).  It's about flat ones, so if you're trying to do this, you
  486.     may be going about it the wrong way or using the wrong tools.  You
  487.     might try parallel arrays with common subscripts.
  488.  
  489.     But if you're bound and determined, you can use the multi-dimensional
  490.     array emulation of $a{'x','y','z'}, or you can make an array of names
  491.     of arrays and eval it.
  492.  
  493.     For example, if @name contains a list of names of arrays, you can 
  494.     get at a the j-th element of the i-th array like so:
  495.  
  496.     $ary = $name[$i];
  497.     $val = eval "\$$ary[$j]";
  498.  
  499.     or in one line
  500.  
  501.     $val = eval "\$$name[$i][\$j]";
  502.  
  503.     You could also use the type-globbing syntax to make an array of *name
  504.     values, which will be more efficient than eval.  Here @name hold
  505.     a list of pointers, which we'll have to dereference through a temporary
  506.     variable.
  507.  
  508.     For example:
  509.  
  510.     { local(*ary) = $name[$i]; $val = $ary[$j]; }
  511.  
  512.     In fact, you can use this method to make arbitrarily nested data
  513.     structures.  You really have to want to do this kind of thing
  514.     badly to go this far, however, as it is notationally cumbersome.
  515.  
  516.     Let's assume you just simply *have* to have an array of arrays of
  517.     arrays.  What you do is make an array of pointers to arrays of
  518.     pointers, where pointers are *name values described above.  You
  519.     initialize the outermost array normally, and then you build up your
  520.     pointers from there.  For example:
  521.  
  522.     @w = ( 'ww' .. 'xx' );
  523.     @x = ( 'xx' .. 'yy' );
  524.     @y = ( 'yy' .. 'zz' );
  525.     @z = ( 'zz' .. 'zzz' );
  526.  
  527.     @ww = reverse @w;
  528.     @xx = reverse @x;
  529.     @yy = reverse @y;
  530.     @zz = reverse @z;
  531.  
  532.     Now make a couple of array of pointers to these:
  533.  
  534.     @A = ( *w, *x, *y, *z );
  535.     @B = ( *ww, *xx, *yy, *zz );
  536.  
  537.     And finally make an array of pointers to these arrays:
  538.  
  539.     @AAA = ( *A, *B );
  540.  
  541.     To access an element, such as AAA[i][j][k], you must do this:
  542.  
  543.     local(*foo) = $AAA[$i];
  544.     local(*bar) = $foo[$j];
  545.     $answer = $bar[$k];
  546.  
  547.     Similar manipulations on associative arrays are also feasible.
  548.  
  549.     You could take a look at recurse.pl package posted by Felix Lee
  550.     <flee@cs.psu.edu>, which lets you simulate vectors and tables (lists and
  551.     associative arrays) by using type glob references and some pretty serious
  552.     wizardry.
  553.  
  554.     In C, you're used to creating recursive datatypes for operations
  555.     like recursive decent parsing or tree traversal.  In Perl, these
  556.     algorithms are best implemented using associative arrays.  Take an
  557.     array called %parent, and build up pointers such that $parent{$person}
  558.     is the name of that person's parent.  Make sure you remember that
  559.     $parent{'adam'} is 'adam'. :-) With a little care, this approach can
  560.     be used to implement general graph traversal algorithms as well.
  561.  
  562.     In Perl5, it's quite easy to declare these things.  For example
  563.  
  564.     @A = (
  565.         [ 'ww' .. 'xx'  ], 
  566.         [ 'xx' .. 'yy'  ], 
  567.         [ 'yy' .. 'zz'  ], 
  568.         [ 'zz' .. 'zzz' ], 
  569.     );
  570.  
  571.     And now reference $A[2]->[0] to pull out "yy".  These may also nest
  572.     and mix with tables:
  573.  
  574.     %T = (
  575.         key0, { k0, v0, k1, v1 },    
  576.         key1, { k2, v2, k3, v3 },    
  577.         key2, { k2, v2, k3, [ 0, 'a' .. 'z' ] },    
  578.     );
  579.     
  580.     Allosing you to reference $T{key2}->{k3}->[3] to pull out 'c'.
  581.  
  582.  
  583.  
  584. 2.11) How do I make an array of structures containing various data types?
  585.  
  586.     Well, soon you may not have to, but for now, let's look at ways to 
  587.     synthesize these.
  588.  
  589.     One scheme I've invented uses what I call pseudoanonymous packages.
  590.     This was motivated because I wanted an associative array of structures
  591.     in which each structure contained not merely scalar data, but also lists
  592.     and tables.   
  593.  
  594.     The table (read: associative array) is called %Active_Folders, whose
  595.     key is the name of the folder, and whose values are, well, *logically*
  596.     they're each a structure whose components look like this:
  597.  
  598.     $Current_Folder
  599.     $Current_Seq  
  600.     $Current_Line
  601.     $Top_Line   
  602.     $Incomplete_Read    
  603.     $Folder_ID  
  604.     $Last_Typed 
  605.     @Scan_Lines
  606.     %Scan_IDs 
  607.     %Deleted 
  608.  
  609.     The way it works is that I only have one folder active at once.
  610.     Those symbols as listed above are accessible from anywhere in the
  611.     program.  The trick is that when I want to switch folders, I change
  612.     what they point to!  You see, there's a package for each folder name
  613.     that contains the real data.  So, it's not like I get to dereference
  614.  
  615.     $Active_Folder{$foldername}->$Current_Line
  616.  
  617.     or 
  618.     $Active_Folder{$foldername}->$Scan_IDs{$msgnum}
  619.  
  620.     Although I'd like to.  I have to switch folders to $foldername first,
  621.     and then access the individual fields directly.  The package isn't intuitable,
  622.     which is why it's a pseudoanonymous one.
  623.  
  624.     Hm, I've this scary feeling that in Perl5, the last line will really read:
  625.  
  626.     ${$Active_Folder{$foldername}->Scan_IDs}->{$msgnum}
  627.  
  628.     or something, which is truly impossible for my brain to parse.  But I'm not
  629.     real clear on it.  I get muddled up part way through whenever Larry explains
  630.     how multiple levels of deferencing will work, and I'm not even sure I'll be
  631.     able to get away with the above without setting up lots of pointers first.
  632.  
  633.     Anyway, here's the code that allows associative arrays of structures of 
  634.     random data types.  I haven't done more than one level yet, although 
  635.     surely you could embed the value of $Active_Folders{$folder} as a $Prev_Folder
  636.     field in each, then do the right appropriate thing.
  637.  
  638.     sub gensym { 'gensym_' . ++$gensym'symbol } 
  639.  
  640.     sub activate_folder {
  641.         local($folder) = @_;
  642.  
  643.         &assert('$folder',$folder);
  644.  
  645.         $Last_Seq = $Current_Seq;
  646.  
  647.         if (! defined $Active_Folders{$folder}) {
  648.         $Active_Folders{$folder} = &gensym;
  649.         push(@Active_Folders, $folder);
  650.         }
  651.  
  652.         local($package) = $Active_Folders{$folder};
  653.  
  654.         local($code)=<<"EOF";
  655.         {
  656.             package $package;
  657.             *'Current_Folder    = *Current_Folder;
  658.             *'Current_Seq       = *Current_Seq;
  659.             *'Current_Line      = *Current_Line;
  660.             *'Top_Line          = *Top_Line;
  661.             *'Scan_Lines        = *Scan_Lines;
  662.             *'Scan_IDs          = *Scan_IDs;
  663.             *'Incomplete_Read   = *Incomplete_Read;
  664.             *'Folder_ID         = *Folder_ID;
  665.             *'Last_Typed        = *Last_Typed;
  666.             *'Deleted           = *Deleted;
  667.             }
  668.         EOF
  669.         eval $code;
  670.         $Current_Seq = $folder;
  671.  
  672.         &panic("bad eval: $@\n$code\n") if $@;
  673.     } 
  674.  
  675.  
  676. 2.12) How can I quote a variable to use in a regexp?
  677.  
  678.     From the manual:
  679.  
  680.     $pattern =~ s/(\W)/\\$1/g;
  681.  
  682.     Now you can freely use /$pattern/ without fear of any unexpected
  683.     meta-characters in it throwing off the search.  If you don't know
  684.     whether a pattern is valid or not, enclose it in an eval to avoid
  685.     a fatal run-time error.
  686.  
  687.  
  688. 2.13) Why do setuid Perl scripts complain about kernel problems?
  689.  
  690.     This message:
  691.  
  692.     YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!
  693.     FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!
  694.  
  695.     is triggered because setuid scripts are inherently insecure due to a
  696.     kernel bug.  If your system has fixed this bug, you can compile Perl
  697.     so that it knows this.  Otherwise, create a setuid C program that just
  698.     execs Perl with the full name of the script.  Larry's wrapsuid 
  699.     script can help.
  700.  
  701.  
  702. 2.14) How do I open a pipe both to and from a command?
  703.  
  704.     In general, this is a dangerous move because you can find yourself in a
  705.     deadlock situation.  It's better to put one end of the pipe to a file.
  706.     For example:
  707.  
  708.     # first write some_cmd's input into a_file, then 
  709.     open(CMD, "some_cmd its_args < a_file |");
  710.     while (<CMD>) {
  711.  
  712.     # or else the other way; run the cmd
  713.     open(CMD, "| some_cmd its_args > a_file");
  714.     while ($condition) {
  715.         print CMD "some output\n";
  716.         # other code deleted
  717.     } 
  718.     close CMD || warn "cmd exited $?";
  719.  
  720.     # now read the file
  721.     open(FILE,"a_file");
  722.     while (<FILE>) {
  723.  
  724.     If you have ptys, you could arrange to run the command on a pty and
  725.     avoid the deadlock problem.  See the chat2.pl package in the
  726.     distributed library for ways to do this.
  727.  
  728.     At the risk of deadlock, it is theoretically possible to use a
  729.     fork, two pipe calls, and an exec to manually set up the two-way
  730.     pipe.  (BSD system may use socketpair() in place of the two pipes,
  731.     but this is not as portable.)  The open2 library function distributed
  732.     with the current perl release will do this for you.
  733.  
  734.     It assumes it's going to talk to something like adb, both writing to
  735.     it and reading from it.  This is presumably safe because you "know"
  736.     that commands like adb will read a line at a time and output a line at
  737.     a time.  Programs like sort that read their entire input stream first,
  738.     however, are quite apt to cause deadlock.
  739.  
  740.  
  741. 2.15) How can I change the first N letters of a string?
  742.  
  743.     Remember that the substr() function produces an lvalue, that is, it may be
  744.     assigned to.  Therefore, to change the first character to an S, you could
  745.     do this:
  746.  
  747.     substr($var,0,1) = 'S';
  748.  
  749.     This assumes that $[ is 0;  for a library routine where you can't know $[,
  750.     you should use this instead:
  751.  
  752.     substr($var,$[,1) = 'S';
  753.  
  754.     While it would be slower, you could in this case use a substitute:
  755.  
  756.     $var =~ s/^./S/;
  757.     
  758.     But this won't work if the string is empty or its first character is a
  759.     newline, which "." will never match.  So you could use this instead:
  760.  
  761.     $var =~ s/^[^\0]?/S/;
  762.  
  763.     To do things like translation of the first part of a string, use substr,
  764.     as in:
  765.  
  766.     substr($var, $[, 10) =~ tr/a-z/A-Z/;
  767.  
  768.     If you don't know then length of what to translate, something like
  769.     this works:
  770.  
  771.     /^(\S+)/ && substr($_,$[,length($1)) =~ tr/a-z/A-Z/;
  772.     
  773.     For some things it's convenient to use the /e switch of the 
  774.     substitute operator:
  775.  
  776.     s/^(\S+)/($tmp = $1) =~ tr#a-z#A-Z#, $tmp/e
  777.  
  778.     although in this case, it runs more slowly than does the previous example.
  779.  
  780.  
  781. 2.16) How can I manipulate fixed-record-length files?
  782.  
  783.     The most efficient way is using pack and unpack.  This is faster than
  784.     using substr.  Here is a sample chunk of code to break up and put back
  785.     together again some fixed-format input lines, in this case, from ps.
  786.  
  787.     # sample input line:
  788.     #   15158 p5  T      0:00 perl /mnt/tchrist/scripts/now-what
  789.     $ps_t = 'A6 A4 A7 A5 A*';
  790.     open(PS, "ps|");
  791.     $_ = <PS>; print;
  792.     while (<PS>) {
  793.         ($pid, $tt, $stat, $time, $command) = unpack($ps_t, $_);
  794.         for $var ('pid', 'tt', 'stat', 'time', 'command' ) {
  795.         print "$var: <", eval "\$$var", ">\n";
  796.         }
  797.         print 'line=', pack($ps_t, $pid, $tt, $stat, $time, $command),  "\n";
  798.     }
  799.  
  800.  
  801. 2.17) How can I make a file handle local to a subroutine?
  802.  
  803.     You must use the type-globbing *VAR notation.  Here is some code to
  804.     cat an include file, calling itself recursively on nested local
  805.     include files (i.e. those with #include "file", not #include <file>):
  806.  
  807.     sub cat_include {
  808.         local($name) = @_;
  809.         local(*FILE);
  810.         local($_);
  811.  
  812.         warn "<INCLUDING $name>\n";
  813.         if (!open (FILE, $name)) {
  814.         warn "can't open $name: $!\n";
  815.         return;
  816.         }
  817.         while (<FILE>) {
  818.         if (/^#\s*include "([^"]*)"/) {
  819.             &cat_include($1);
  820.         } else {
  821.             print;
  822.         }
  823.         }
  824.         close FILE;
  825.     }
  826.  
  827.  
  828. 2.18) How can I extract just the unique elements of an array?
  829.  
  830.     There are several possible ways, depending on whether the
  831.     array is ordered and you wish to preserve the ordering.
  832.  
  833.     a) If @in is sorted, and you want @out to be sorted:
  834.  
  835.     $prev = 'nonesuch';
  836.     @out = grep($_ ne $prev && (($prev) = $_), @in);
  837.  
  838.        This is nice in that it doesn't use much extra memory, 
  839.        simulating uniq's behavior of removing only adjacent
  840.        duplicates.
  841.  
  842.     b) If you don't know whether @in is sorted:
  843.  
  844.     undef %saw;
  845.     @out = grep(!$saw{$_}++, @in);
  846.  
  847.     c) Like (b), but @in contains only small integers:
  848.  
  849.     @out = grep(!$saw[$_]++, @in);
  850.  
  851.     d) A way to do (b) without any loops or greps:
  852.  
  853.     undef %saw;
  854.     @saw{@in} = ();
  855.     @out = sort keys %saw;  # remove sort if undesired
  856.  
  857.     e) Like (d), but @in contains only small positive integers:
  858.  
  859.     undef @ary;
  860.     @ary[@in] = @in;
  861.     @out = sort @ary;
  862.  
  863.  
  864. 2.19) How can I call alarm() or usleep() from Perl?
  865.  
  866.     It's available as a built-in as of version 3.038.  If you want finer
  867.     granularity than 1 second (as usleep() provides) and have itimers and
  868.     syscall() on your system, you can use the following.  You could also
  869.     use select().
  870.  
  871.     It takes a floating-point number representing how long to delay until
  872.     you get the SIGALRM, and returns a floating- point number representing
  873.     how much time was left in the old timer, if any.  Note that the C
  874.     function uses integers, but this one doesn't mind fractional numbers.
  875.  
  876.     # alarm; send me a SIGALRM in this many seconds (fractions ok)
  877.     # tom christiansen <tchrist@convex.com>
  878.     sub alarm {
  879.     require 'syscall.ph';
  880.     require 'sys/time.ph';
  881.  
  882.     local($ticks) = @_;
  883.     local($in_timer,$out_timer);
  884.     local($isecs, $iusecs, $secs, $usecs);
  885.  
  886.     local($itimer_t) = 'L4'; # should be &itimer'typedef()
  887.  
  888.     $secs = int($ticks);
  889.     $usecs = ($ticks - $secs) * 1e6;
  890.  
  891.     $out_timer = pack($itimer_t,0,0,0,0);  
  892.     $in_timer  = pack($itimer_t,0,0,$secs,$usecs);
  893.  
  894.     syscall(&SYS_setitimer, &ITIMER_REAL, $in_timer, $out_timer)
  895.         && die "alarm: setitimer syscall failed: $!";
  896.  
  897.     ($isecs, $iusecs, $secs, $usecs) = unpack($itimer_t,$out_timer);
  898.     return $secs + ($usecs/1e6);
  899.     }
  900.  
  901.  
  902. 2.20) How can I test whether an array contains a certain element?
  903.  
  904.     There are several ways to approach this.  If you are going to make
  905.     this query many times and the values are arbitrary strings, the
  906.     fastest way is probably to invert the original array and keep an
  907.     associative array lying about whose keys are the first array's values.
  908.  
  909.     @blues = ('turquoise', 'teal', 'lapis lazuli');
  910.     undef %is_blue;
  911.     for (@blues) { $is_blue{$_} = 1; }
  912.  
  913.     Now you can check whether $is_blue{$some_color}.  It might have been
  914.     a good idea to keep the blues all in an assoc array in the first place.
  915.  
  916.     If the values are all small integers, you could use a simple
  917.     indexed array.  This kind of an array will take up less space:
  918.  
  919.     @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
  920.     undef @is_tiny_prime;
  921.     for (@primes) { $is_tiny_prime[$_] = 1; }
  922.  
  923.     Now you check whether $is_tiny_prime[$some_number].
  924.  
  925.     If the values in question are integers, but instead of strings,
  926.     you can save quite a lot of space by using bit strings instead:
  927.  
  928.     @articles = ( 1..10, 150..2000, 2017 );
  929.     undef $read;
  930.     grep (vec($read,$_,1) = 1, @articles);
  931.     
  932.     Now check whether vec($read,$n,1) is true for some $n.
  933.  
  934.  
  935. 2.21) How can I do an atexit() or setjmp()/longjmp() in Perl?
  936.  
  937.     Perl's exception-handling mechanism is its eval operator.  You 
  938.     can use eval as setjmp and die as longjmp.  Here's an example
  939.     of Larry's for timed-out input, which in C is often implemented
  940.     using setjmp and longjmp:
  941.  
  942.       $SIG{ALRM} = TIMEOUT;
  943.       sub TIMEOUT { die "restart input\n" }
  944.  
  945.       do { eval { &realcode } } while $@ =~ /^restart input/;
  946.  
  947.       sub realcode {
  948.           alarm 15;
  949.           $ans = <STDIN>;
  950.           alarm 0;
  951.       }
  952.  
  953.    Here's an example of Tom's for doing atexit() handling:
  954.  
  955.     sub atexit { push(@_exit_subs, @_) }
  956.  
  957.     sub _cleanup { unlink $tmp }
  958.  
  959.     &atexit('_cleanup');
  960.  
  961.     eval <<'End_Of_Eval';  $here = __LINE__;
  962.     # as much code here as you want
  963.     End_Of_Eval
  964.  
  965.     $oops = $@;  # save error message
  966.  
  967.     # now call his stuff
  968.     for (@_exit_subs) { &$_() }
  969.  
  970.     $oops && ($oops =~ s/\(eval\) line (\d+)/$0 .
  971.         " line " . ($1+$here)/e, die $oops);
  972.  
  973.     You can register your own routines via the &atexit function now.  You
  974.     might also want to use the &realcode method of Larry's rather than
  975.     embedding all your code in the here-is document.  Make sure to leave
  976.     via die rather than exit, or write your own &exit routine and call
  977.     that instead.   In general, it's better for nested routines to exit
  978.     via die rather than exit for just this reason.
  979.  
  980.     In Perl5, it will be easy to set this up because of the automatic
  981.     processing of per-package END functions.
  982.  
  983.     Eval is also quite useful for testing for system dependent features,
  984.     like symlinks, or using a user-input regexp that might otherwise
  985.     blowup on you.
  986.  
  987.  
  988. 2.22) Why doesn't Perl interpret my octal data octally?
  989.  
  990.     Perl only understands octal and hex numbers as such when they occur
  991.     as constants in your program.  If they are read in from somewhere
  992.     and assigned, then no automatic conversion takes place.  You must
  993.     explicitly use oct() or hex() if you want this kind of thing to happen.
  994.     Actually, oct() knows to interpret both hex and octal numbers, while
  995.     hex only converts hexadecimal ones.  For example:
  996.  
  997.     {
  998.         print "What mode would you like? ";
  999.         $mode = <STDIN>;
  1000.         $mode = oct($mode);
  1001.         unless ($mode) {
  1002.         print "You can't really want mode 0!\n";
  1003.         redo;
  1004.         } 
  1005.         chmod $mode, $file;
  1006.     } 
  1007.  
  1008.     Without the octal conversion, a requested mode of 755 would turn 
  1009.     into 01363, yielding bizarre file permissions of --wxrw--wt.
  1010.  
  1011.     If you want something that handles decimal, octal and hex input, 
  1012.     you could follow the suggestion in the man page and use:
  1013.  
  1014.     $val = oct($val) if $val =~ /^0/;
  1015.  
  1016. 2.23) How do I sort an associative array by value instead of by key?
  1017.  
  1018.     You have to declare a sort subroutine to do this.  Let's assume
  1019.     you want an ASCII sort on the values of the associative array %ary.
  1020.     You could do so this way:
  1021.  
  1022.     foreach $key (sort by_value keys %ary) {
  1023.         print $key, '=', $ary{$key}, "\n";
  1024.     } 
  1025.     sub by_value { $ary{$a} cmp $ary{$b}; }
  1026.  
  1027.     If you wanted a descending numeric sort, you could do this:
  1028.  
  1029.     sub by_value { $ary{$b} <=> $ary{$a}; }
  1030.  
  1031.     You can also inline your sort function, like this, at least if 
  1032.     you have a relatively recent patchlevel of perl4:
  1033.  
  1034.     foreach $key ( sort { $ary{$b} <=> $ary{$a} } keys %ary ) {
  1035.         print $key, '=', $ary{$key}, "\n";
  1036.     } 
  1037.  
  1038.     If you wanted a function that didn't have the array name hard-wired
  1039.     into it, you could so this:
  1040.  
  1041.     foreach $key (&sort_by_value(*ary)) {
  1042.         print $key, '=', $ary{$key}, "\n";
  1043.     } 
  1044.     sub sort_by_value {
  1045.         local(*x) = @_;
  1046.         sub _by_value { $x{$a} cmp $x{$b}; } 
  1047.         sort _by_value keys %x;
  1048.     } 
  1049.  
  1050.     If you want neither an alphabetic nor a numeric sort, then you'll 
  1051.     have to code in your own logic instead of relying on the built-in
  1052.     signed comparison operators "cmp" and "<=>".
  1053.  
  1054.     Note that if you're sorting on just a part of the value, such as a
  1055.     piece you might extract via split, unpack, pattern-matching, or
  1056.     substr, then rather than performing that operation inside your sort
  1057.     routine on each call to it, it is significantly more efficient to
  1058.     build a parallel array of just those portions you're sorting on, sort
  1059.     the indices of this parallel array, and then to subscript your original
  1060.     array using the newly sorted indices.  This method works on both
  1061.     regular and associative arrays, since both @ary[@idx] and @ary{@idx}
  1062.     make sense.  See page 245 in the Camel Book on "Sorting an Array by a
  1063.     Computable Field" for a simple example of this.
  1064.  
  1065.  
  1066. 2.24) How can I capture STDERR from an external command?
  1067.  
  1068.     There are three basic ways of running external commands:
  1069.  
  1070.     system $cmd;
  1071.     $output = `$cmd`;
  1072.     open (PIPE, "cmd |");
  1073.  
  1074.     In the first case, both STDOUT and STDERR will go the same place as
  1075.     the script's versions of these, unless redirected.  You can always put
  1076.     them where you want them and then read them back when the system
  1077.     returns.  In the second and third cases, you are reading the STDOUT
  1078.     *only* of your command.  If you would like to have merged STDOUT and
  1079.     STDERR, you can use shell file-descriptor redirection to dup STDERR to
  1080.     STDOUT:
  1081.  
  1082.     $output = `$cmd 2>&1`;
  1083.     open (PIPE, "cmd 2>&1 |");
  1084.  
  1085.     Another possibility is to run STDERR into a file and read the file 
  1086.     later, as in 
  1087.  
  1088.     $output = `$cmd 2>some_file`;
  1089.     open (PIPE, "cmd 2>some_file |");
  1090.     
  1091.     Here's a way to read from both of them and know which descriptor
  1092.     you got each line from.  The trick is to pipe only STDERR through
  1093.     sed, which then marks each of its lines, and then sends that
  1094.     back into a merged STDOUT/STDERR stream, from which your Perl program
  1095.     then reads a line at a time:
  1096.  
  1097.         open (CMD, 
  1098.           "3>&1 (cmd args 2>&1 1>&3 3>&- | sed 's/^/STDERR:/' 3>&-) 3>&- |");
  1099.  
  1100.         while (<CMD>) {
  1101.           if (s/^STDERR://)  {
  1102.               print "line from stderr: ", $_;
  1103.           } else {
  1104.               print "line from stdout: ", $_;
  1105.           }
  1106.         }
  1107.  
  1108.     Be apprised that you *must* use Bourne shell redirection syntax
  1109.     here, not csh!  In fact, you can't even do these things with csh.
  1110.     For details on how lucky you are that perl's system() and backtick
  1111.     and pipe opens all use Bourne shell, fetch the file from convex.com
  1112.     called /pub/csh.whynot -- and you'll be glad that perl's shell
  1113.     interface is the Bourne shell.
  1114.  
  1115.     There's an &open3 routine out there which will be merged with 
  1116.     &open2 in perl5 production.
  1117.  
  1118.  
  1119. 2.25) Why doesn't open return an error when a pipe open fails?
  1120.  
  1121.     These statements:
  1122.  
  1123.     open(TOPIPE, "|bogus_command") || die ...
  1124.     open(FROMPIPE, "bogus_command|") || die ...
  1125.  
  1126.     will not fail just for lack of the bogus_command.  They'll only
  1127.     fail if the fork to run them fails, which is seldom the problem.
  1128.  
  1129.     If you're writing to the TOPIPE, you'll get a SIGPIPE if the child
  1130.     exits prematurely or doesn't run.  If you are reading from the
  1131.     FROMPIPE, you need to check the close() to see what happened.
  1132.  
  1133.     If you want an answer sooner than pipe buffering might otherwise
  1134.     afford you, you can do something like this:
  1135.  
  1136.     $kid = open (PIPE, "bogus_command |");   # XXX: check defined($kid)
  1137.     (kill 0, $kid) || die "bogus_command failed";
  1138.  
  1139.     This works fine if bogus_command doesn't have shell metas in it, but
  1140.     if it does, the shell may well not have exited before the kill 0.  You
  1141.     could always introduce a delay:
  1142.  
  1143.     $kid = open (PIPE, "bogus_command </dev/null |");
  1144.     sleep 1;
  1145.     (kill 0, $kid) || die "bogus_command failed";
  1146.  
  1147.     but this is sometimes undesirable, and in any event does not guarantee
  1148.     correct behavior.  But it seems slightly better than nothing.
  1149.  
  1150.     Similar tricks can be played with writable pipes if you don't wish to
  1151.     catch the SIGPIPE.
  1152.  
  1153.  
  1154. 2.26) How can I compare two date strings?
  1155.  
  1156.     If the dates are in an easily parsed, predetermined format, then you
  1157.     can break them up into their component parts and call &timelocal from
  1158.     the distributed perl library.  If the date strings are in arbitrary
  1159.     formats, however, it's probably easier to use the getdate program
  1160.     from the Cnews distribution, since it accepts a wide variety of dates.
  1161.     Note that in either case the return values you will really be
  1162.     comparing will be the total time in seconds as return by time().
  1163.    
  1164.     Here's a getdate function for perl that's not very efficient; you 
  1165.     can do better this by sending it many dates at once or modifying
  1166.     getdate to behave better on a pipe.  Beware the hardcoded pathname.
  1167.  
  1168.     sub getdate {
  1169.         local($_) = shift;
  1170.  
  1171.         s/-(\d{4})$/+$1/ || s/\+(\d{4})$/-$1/; 
  1172.         # getdate has broken timezone sign reversal!
  1173.  
  1174.         $_ = `/usr/local/lib/news/newsbin/getdate '$_'`;
  1175.         chop;
  1176.         $_;
  1177.     } 
  1178.  
  1179.     Richard Ohnemus <rick@IMD.Sterling.COM> actually has a getdate.y
  1180.     for use with the Perl yacc.  You can get this from ftp.sterling.com
  1181.     [192.124.9.1] in /local/perl-byacc1.8.1.tar.Z, or send the author
  1182.     mail for details.
  1183.  
  1184.     You might also consider using these: 
  1185.  
  1186.     date.pl        - print dates how you want with the sysv +FORMAT method
  1187.     date.shar      - routines to manipulate and calculate dates
  1188.     ftp-chat2.shar - updated version of ftpget. includes library and demo programs
  1189.     getdate.shar   - returns number of seconds since epoch for any given date
  1190.     ptime.shar     - print dates how you want with the sysv +FORMAT method
  1191.  
  1192.     You probably want 'getdate.shar'... these and other files can be ftp'd from
  1193.     the /pub/perl/scripts directory on coombs.anu.edu.au. See the README file in
  1194.     the /pub/perl directory for time and the European mirror site details.
  1195.  
  1196.  
  1197. 2.27) What's the fastest way to code up a given task in perl?
  1198.  
  1199.     Because Perl so lends itself to a variety of different approaches
  1200.     for any given task, a common question is which is the fastest way
  1201.     to code a given task.  Since some approaches can be dramatically
  1202.     more efficient that others, it's sometimes worth knowing which is
  1203.     best.  Unfortunately, the implementation that first comes to mind,
  1204.     perhaps as a direct translation from C or the shell, often yields
  1205.     suboptimal performance.  Not all approaches have the same results
  1206.     across different hardware and software platforms.  Furthermore,
  1207.     legibility must sometimes be sacrificed for speed.
  1208.  
  1209.     While an experienced perl programmer can sometimes eye-ball the code
  1210.     and make an educated guess regarding which way would be fastest,
  1211.     surprises can still occur.  So, in the spirit of perl programming
  1212.     being an empirical science, the best way to find out which of several
  1213.     different methods runs the fastest is simply to code them all up and
  1214.     time them. For example:
  1215.  
  1216.     $COUNT = 10_000; $| = 1;
  1217.  
  1218.     print "method 1: ";
  1219.  
  1220.         ($u, $s) = times;
  1221.         for ($i = 0; $i < $COUNT; $i++) {
  1222.         # code for method 1
  1223.         }
  1224.         ($nu, $ns) = times;
  1225.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  1226.  
  1227.     print "method 2: ";
  1228.  
  1229.         ($u, $s) = times;
  1230.         for ($i = 0; $i < $COUNT; $i++) {
  1231.         # code for method 2
  1232.         }
  1233.         ($nu, $ns) = times;
  1234.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  1235.  
  1236.     For more specific tips, see the section on Efficiency in the
  1237.     ``Other Oddments'' chapter at the end of the Camel Book.
  1238.  
  1239.  
  1240. 2.28) How can I know how many entries are in an associative array?
  1241.  
  1242.     While the number of elements in a @foobar array is simply @foobar when
  1243.     used in a scalar, you can't figure out how many elements are in an
  1244.     associative array in an analogous fashion.  That's because %foobar in
  1245.     a scalar context returns the ratio (as a string) of number of buckets
  1246.     filled versus the number allocated.  For example, scalar(%ENV) might
  1247.     return "20/32".  While perl could in theory keep a count, this would
  1248.     break down on associative arrays that have been bound to dbm files.
  1249.  
  1250.     However, while you can't get a count this way, one thing you *can* use
  1251.     it for is to determine whether there are any elements whatsoever in
  1252.     the array, since "if (%table)" is guaranteed to be false if nothing
  1253.     has ever been stored in it.  
  1254.  
  1255.     So you either have to keep your own count around and increments
  1256.     it every time you store a new key in the array, or else do it
  1257.     on the fly when you really care, perhaps like this:
  1258.  
  1259.     $count++ while each %ENV;
  1260.  
  1261.     This preceding method will be faster than extracting the
  1262.     keys into a temporary array to count them.
  1263.  
  1264.     As of a very recent patch, you can say
  1265.  
  1266.     $count = keys %ENV;
  1267. -- 
  1268.     Tom Christiansen      tchrist@cs.colorado.edu       
  1269.             Consultant
  1270.     Boulder Colorado  303-444-3212
  1271.  
  1272.